package com.hen.web.henweb.jwt.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Date;

/**
 * @author 狠穿
 * @version 1.0.0
 * @date 2023/4/6
 * @function Token相关的API封装
 */
public class TokenUtil {

    /**
     * 过期时间 1h
     */
    private static Long expireTime = 1000 * 5L;

    /**
     * 发行人
     */
    private static String ISSUER = "ADMIN";

    /**
     * 私钥
     */
    private static final String SECRET = "2mFBhqzZowt3p7zQrTCXQRFoFHfT3VVVuU46Rzzs";

    /**
     * 基于用户名生成Token字符串
     * @param userName 用户名
     * @return 生成的Token字符串
     */
    public static String createToken(String userName){
        Date now = Calendar.getInstance().getTime();
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        return JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime()+expireTime))
                .withClaim("userName",userName)
                .sign(algorithm);
    }

    /**
     * 从Token字符串中解析出用户名
     * @param token 待解析的Token字符串
     * @return
     */
    public static String parseToken(String token){
        String userName;
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        JWTVerifier jwtVerifier = JWT.require(algorithm)
                .withIssuer(ISSUER)
                .build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        userName = decodedJWT.getClaim("userName").asString();
        return userName;
    }

}
